import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fl_chart/fl_chart.dart';
import '../providers/vpn_provider.dart';
import '../utils/formatters.dart';
import '../utils/theme.dart';
import '../l10n/app_localizations.dart';

class TrafficMonitor extends StatefulWidget {
  const TrafficMonitor({super.key});

  @override
  State<TrafficMonitor> createState() => _TrafficMonitorState();
}

class _TrafficMonitorState extends State<TrafficMonitor> {
  String _selectedPeriod = 'today';

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);

    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  l10n.translate('feature_traffic_monitor'),
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SegmentedButton<String>(
                  segments: [
                    ButtonSegment(
                      value: 'today',
                      label: Text(l10n.translate('stats_today')),
                    ),
                    ButtonSegment(
                      value: 'week',
                      label: Text(l10n.translate('stats_this_week')),
                    ),
                    ButtonSegment(
                      value: 'month',
                      label: Text(l10n.translate('stats_this_month')),
                    ),
                  ],
                  selected: {_selectedPeriod},
                  onSelectionChanged: (Set<String> selected) {
                    setState(() {
                      _selectedPeriod = selected.first;
                    });
                  },
                ),
              ],
            ),
            const SizedBox(height: 20),
            Consumer<VpnProvider>(
              builder: (context, vpnProvider, _) {
                final stats = vpnProvider.currentStats;
                
                if (stats == null) {
                  return const Center(
                    child: Padding(
                      padding: EdgeInsets.all(40),
                      child: Text('No data available'),
                    ),
                  );
                }

                return Column(
                  children: [
                    // Stats summary
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        _buildStatCard(
                          icon: Icons.cloud_upload,
                          label: l10n.trafficUpload,
                          value: formatBytes(stats.totalUpload),
                          color: AppTheme.primaryColor,
                        ),
                        _buildStatCard(
                          icon: Icons.cloud_download,
                          label: l10n.trafficDownload,
                          value: formatBytes(stats.totalDownload),
                          color: AppTheme.secondaryColor,
                        ),
                        _buildStatCard(
                          icon: Icons.compare_arrows,
                          label: l10n.trafficTotal,
                          value: formatBytes(
                              stats.totalUpload + stats.totalDownload),
                          color: Colors.purple,
                        ),
                      ],
                    ),
                    const SizedBox(height: 24),
                    
                    // Chart
                    SizedBox(
                      height: 200,
                      child: _buildTrafficChart(stats, l10n),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // Speed info
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade50,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          _buildSpeedInfo(
                            icon: Icons.speed,
                            label: l10n.translate('stats_avg_speed'),
                            value: formatSpeed(
                                ((stats.uploadSpeed + stats.downloadSpeed) / 2).toInt()),
                            color: Colors.blue,
                          ),
                          Container(
                            width: 1,
                            height: 40,
                            color: Colors.grey.shade300,
                          ),
                          _buildSpeedInfo(
                            icon: Icons.trending_up,
                            label: l10n.translate('stats_peak_speed'),
                            value: formatSpeed(stats.downloadSpeed),
                            color: Colors.orange,
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatCard({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(icon, color: color, size: 24),
        ),
        const SizedBox(height: 8),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey.shade600,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  Widget _buildSpeedInfo({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Row(
      children: [
        Icon(icon, color: color, size: 20),
        const SizedBox(width: 8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              label,
              style: TextStyle(
                fontSize: 11,
                color: Colors.grey.shade600,
              ),
            ),
            Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: color,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildTrafficChart(dynamic stats, AppLocalizations l10n) {
    return LineChart(
      LineChartData(
        gridData: FlGridData(
          show: true,
          drawVerticalLine: false,
          horizontalInterval: 1,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: Colors.grey.shade200,
              strokeWidth: 1,
            );
          },
        ),
        titlesData: FlTitlesData(
          show: true,
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 30,
              interval: 1,
              getTitlesWidget: (value, meta) {
                const style = TextStyle(
                  fontSize: 10,
                  color: Colors.grey,
                );
                String text;
                switch (value.toInt()) {
                  case 0:
                    text = '0m';
                    break;
                  case 1:
                    text = '5m';
                    break;
                  case 2:
                    text = '10m';
                    break;
                  case 3:
                    text = '15m';
                    break;
                  case 4:
                    text = '20m';
                    break;
                  case 5:
                    text = '25m';
                    break;
                  case 6:
                    text = '30m';
                    break;
                  default:
                    return const Text('');
                }
                return Text(text, style: style);
              },
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              interval: 1,
              reservedSize: 40,
              getTitlesWidget: (value, meta) {
                return Text(
                  formatSpeed((value * 1024 * 1024).toInt()),
                  style: const TextStyle(
                    fontSize: 10,
                    color: Colors.grey,
                  ),
                );
              },
            ),
          ),
        ),
        borderData: FlBorderData(
          show: true,
          border: Border.all(color: Colors.grey.shade200),
        ),
        minX: 0,
        maxX: 6,
        minY: 0,
        maxY: 5,
        lineBarsData: [
          // Upload line
          LineChartBarData(
            spots: [
              const FlSpot(0, 1),
              const FlSpot(1, 1.5),
              const FlSpot(2, 1.2),
              const FlSpot(3, 2),
              const FlSpot(4, 1.8),
              const FlSpot(5, 2.5),
              const FlSpot(6, 2.3),
            ],
            isCurved: true,
            gradient: LinearGradient(
              colors: [
                AppTheme.primaryColor.withOpacity(0.8),
                AppTheme.primaryColor,
              ],
            ),
            barWidth: 3,
            isStrokeCapRound: true,
            dotData: const FlDotData(show: false),
            belowBarData: BarAreaData(
              show: true,
              gradient: LinearGradient(
                colors: [
                  AppTheme.primaryColor.withOpacity(0.2),
                  AppTheme.primaryColor.withOpacity(0.05),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
          ),
          // Download line
          LineChartBarData(
            spots: [
              const FlSpot(0, 2),
              const FlSpot(1, 2.5),
              const FlSpot(2, 3),
              const FlSpot(3, 2.8),
              const FlSpot(4, 3.5),
              const FlSpot(5, 4),
              const FlSpot(6, 3.8),
            ],
            isCurved: true,
            gradient: LinearGradient(
              colors: [
                AppTheme.secondaryColor.withOpacity(0.8),
                AppTheme.secondaryColor,
              ],
            ),
            barWidth: 3,
            isStrokeCapRound: true,
            dotData: const FlDotData(show: false),
            belowBarData: BarAreaData(
              show: true,
              gradient: LinearGradient(
                colors: [
                  AppTheme.secondaryColor.withOpacity(0.2),
                  AppTheme.secondaryColor.withOpacity(0.05),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
          ),
        ],
        lineTouchData: LineTouchData(
          touchTooltipData: LineTouchTooltipData(
            getTooltipItems: (touchedSpots) {
              return touchedSpots.map((spot) {
                final isUpload = spot.barIndex == 0;
                return LineTooltipItem(
                  '${isUpload ? l10n.trafficUpload : l10n.trafficDownload}\n${formatSpeed((spot.y * 1024 * 1024).toInt())}',
                  TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                );
              }).toList();
            },
          ),
        ),
      ),
    );
  }
}
